package zj.it.bhne.gridengineeringsurvey.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetDialog;
import android.support.v4.app.ActivityCompat;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Polyline;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.map.Text;
import com.baidu.mapapi.map.TextOptions;
import com.baidu.mapapi.map.offline.MKOfflineMap;
import com.baidu.mapapi.map.offline.MKOfflineMapListener;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.LatLngBounds;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.flyco.dialog.widget.ActionSheetDialog;
import com.flyco.dialog.widget.NormalDialog;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

import zj.it.bhne.gridengineeringsurvey.BaseActivity;
import zj.it.bhne.gridengineeringsurvey.MyApplication;
import zj.it.bhne.gridengineeringsurvey.R;
import zj.it.bhne.gridengineeringsurvey.entity.DefaultBean;
import zj.it.bhne.gridengineeringsurvey.entity.Equip;
import zj.it.bhne.gridengineeringsurvey.entity.greendao.Equipment;
import zj.it.bhne.gridengineeringsurvey.entity.greendao.Items;
import zj.it.bhne.gridengineeringsurvey.entity.greendao.Line;
import zj.it.bhne.gridengineeringsurvey.entity.greendao.Points;
import zj.it.bhne.gridengineeringsurvey.myutils.GetToken;
import zj.it.bhne.gridengineeringsurvey.myutils.HttpConfig;
import zj.it.bhne.gridengineeringsurvey.myutils.MyUtils;
import zj.it.bhne.gridengineeringsurvey.myutils.PopupMenu;
import zj.it.bhne.gridengineeringsurvey.myutils.ThreadManager;
import zj.it.bhne.gridengineeringsurvey.myutils.greendao.ItemsDao;
import zj.it.bhne.gridengineeringsurvey.myutils.greendao.LineDao;
import zj.it.bhne.gridengineeringsurvey.myutils.greendao.PointsDao;
import zj.it.bhne.gridengineeringsurvey.myutils.map_activity.ParseXmls;

import static zj.it.bhne.gridengineeringsurvey.activity.EquActivity.setSpinnerItemSelectedByValue;
import static zj.it.bhne.gridengineeringsurvey.myutils.HttpConfig.parseXMLWithPull;
import static zj.it.bhne.gridengineeringsurvey.myutils.MyUtils.Distance;
import static zj.it.bhne.gridengineeringsurvey.myutils.MyUtils.openDatabase;
import static zj.it.bhne.gridengineeringsurvey.myutils.ThreadManager.getThreadPool;

/**
 * 地图踩点的活动
 */
public class MapActivity extends BaseActivity implements View.OnClickListener, SensorEventListener, MKOfflineMapListener {

    //点ID
    public static long bid;
    //项目ID
    public static long zid;
    private final int BAIDU_READ_PHONE_STATE = 96;
    TextView maps_ed_name;
    Spinner maps_sp_type;
    EditText maps_ed_length;
    EditText maps_ed_width;
    TextView maps_tv_location;
    EditText maps_ed_high;
    EditText maps_ed_note;
    Button maps_btn_cancel;
    Button maps_btn_add;
    LinearLayout maps_rl_add;
    private MyLocationListenner myListener = new MyLocationListenner();
    private MyLocationConfiguration.LocationMode mCurrentMode;
    // 定位相关
    private LocationClient mLocClient;
    private MapView mMapView;
    private BaiduMap mBaiduMap;
    private double mCurrentLat = 0.0;
    private double mCurrentLon = 0.0;
    private LatLng lc;
    private MapStatus mapStatuss;
    private List<LatLng> latLngs = new ArrayList<>();
    private Context context;
    private Long cid;
    /*private double latMax;
    private double latMin;
    private double lngMax;
    private double lngMin;*/
    private List<LatLng> latLngPolygon = new ArrayList<>();
    private String glsb;//关联设备
    private SensorManager mSensorManager;
    private Double lastX = 0.0;
    private float mCurrentAccracy;
    private MyLocationData locData;
    private int mCurrentDirection = 0;
    private boolean isFirstLoc = true; // 是否首次定位
    private Button map_btn_length;
    private boolean btn_Length_isCheck = false;
    private Button map_btn_model;
    private Polyline polyline;
    private Boolean btn_model = false;
    private Button map_btn_add;
    //private RelativeLayout map_rl_add;
    private Spinner map_sp_state;
    private TextView map_tv_location;
    private TextView map_ed_name;
    private Button mMapBtnOne, mMapBtnTwo, mMapBtnThree;
    private TextView activity_tv_save;
    private TextView activity_tv_quxiao;
    private Button map_btn_four;
    private ImageView iv_center;
    private boolean MARKER_DEFINE = false;
    private TextView map_sp_sort;
    private Spinner map_sp_type;
    private TextView map_tv_name;
    private ImageButton location;
    private TextView map_tv_dixing_sort;
    private Spinner map_sp_dixing_sort;
    private LinearLayout map_ll_dixing_sort;
    private EditText map_ed_note;
    private Spinner map_sp_equ;
    private EditText map_ed_high;
    private Button map_btn_name;
    private Button map_open_line;
    private boolean btn_Name_isCheck = false;
    private List<Points> pointsList = new ArrayList<>();
    private LinearLayout map_ll_lijiu;
    private LinearLayout map_ll_guanlian;
    private ProgressDialog mProgressDialog;
    private int densityDpi;
    private View view;
    private TextView map_marker;
    private ImageView map_marker_image;
    private Items items;
    //private Button map_btn_change;
    private Bitmap bitmap;
    private Text overlay;
    private boolean jixukance;
    private Long jid;
    private Points jpoints;
    private List<Points> pointsListLine = new ArrayList<>();
    private List<Equip> equipList = new ArrayList<>();
    private String uid;
    private List<Double> latDoubleList = new ArrayList<>();
    private List<Double> lonDoubleList = new ArrayList<>();
    //private Double latA, latB, lonA, lonB;
    private float zoom;
    private String state;
    private double high = 0;
    private BottomSheetDialog bottomSheetDialog;
    private EditText maps_ed_address;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            //若工作完成，取消动画，初始化界面
            mProgressDialog.cancel();
            /*//开始初始化界面
            initView();*/
        }
    };
    /**
     * 线程
     */
    private Runnable mRunnable = () -> {
        /*
            需要耗时的工作
        */
        initData();
        Message msg = mHandler.obtainMessage();
        msg.what = 1;
        mHandler.sendMessage(msg);
    };
    /**
     * 在线项目更新点
     */
    private Runnable mRunnable1 = () -> {
        /*
            需要耗时的工作
        */
        LinkedHashMap map = new LinkedHashMap();
        map.put("surverytaskid", items.getProjectId());
        String result = HttpConfig.callService("getPointsInfo", map);
        ParseXmls.getInstance().parseXMLWithPulls(result, items, cid);
        initData();
        Message msg = mHandler.obtainMessage();
        msg.what = 2;
        mHandler.sendMessage(msg);
    };
    private boolean isOpenOrClose = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SDKInitializer.initialize(getApplicationContext());
        /*实例化 定位客户端*/
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);//获取传感器管理服务
        mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;
        new LocationClient(getApplicationContext());
        /*注册回调方法,显示定位结果信息*/
        setContentView(R.layout.activity_map);
        context = this;

        // 地图初始化
        mMapView = findViewById(R.id.map_mapView);
        mMapView.setOnClickListener(this);

        mBaiduMap = mMapView.getMap();
        Intent intent = getIntent();
        //接收主页面跳转过来的id
        cid = intent.getLongExtra("id", 0);
        state = intent.getStringExtra("name");
        if (state.equals("在线"))
            items = MyApplication.getInstances().getItemsDao().queryBuilder().where(ItemsDao.Properties.Id.eq(cid)).build().list().get(0);
        if (Build.VERSION.SDK_INT >= 23) {
            showContacts();
        } else {
            initMap();//init为定位方法
        }
        initView();

    }

    /**
     * 初始化数据
     */
    private void initData() {
        mBaiduMap.clear();
        pointsList = MyApplication.getInstances().getPointsDao().queryBuilder().where(PointsDao.Properties.Items_id.eq(cid)).build().list();
        //查询本项目中所有的点的信息
        //点信息如果不为空的情况下进行操作
        try {
            if (pointsList.size() > 0) {
                Log.e("plsjfl",pointsList.toString());
                /*[Points{id=1, equ_id=1, high='1.1米', old='新建', lineType='null', items_id=1, note='备注信息：', mark='ZXG-1', sbbh='直线杆', sbzt='null', glsb='null', lat='39.08646762710225', lon='117.09919261745164', weizhi='null', dangju=0.0, name='杆塔', latA='null', latB='null', lonA='null', lonB='null', category='null', equ='null', whether='0', batch='0', sblx='直线杆', uid='6fbf99dd-e73b-469c-ac24-352be48f76ca'},
                Points{id=2, equ_id=1, high='1.1米', old='新建', lineType='null', items_id=1, note='备注信息：', mark='ZXG-2', sbbh='直线杆', sbzt='null', glsb='ZXG-1', lat='39.08610320177811', lon='117.09976908991655', weizhi='null', dangju=64.17, name='杆塔', latA='null', latB='null', lonA='null', lonB='null', category='null', equ='null', whether='0', batch='0', sblx='直线杆', uid='0267cbc2-e2da-4f2e-af47-dcf378baf44f'},
                Points{id=3, equ_id=1, high='1.1米', old='新建', lineType='null', items_id=1, note='备注信息：', mark='ZXG-3', sbbh='直线杆', sbzt='null', glsb='ZXG-2', lat='39.08569273425972', lon='117.0990925409082', weizhi='null', dangju=74.12, name='杆塔', latA='null', latB='null', lonA='null', lonB='null', category='null', equ='null', whether='0', batch='0', sblx='直线杆', uid='bbf6722d-2991-4567-aeca-eacbc28c0f68'},
                Points{id=4, equ_id=23, high='13米', old='新建', lineType='null', items_id=1, note='备注信息：', mark='DLGD-4', sbbh='电缆拐点', sbzt='null', glsb='', lat='39.086099683063175', lon='117.09854864668418', weizhi='null', dangju=0.0, name='地形点', latA='null', latB='null', lonA='null', lonB='null', category='null', equ='null', whether='1', batch='0', sblx='电缆拐点', uid='f3bdb82e-5098-4c99-991d-b321bd24eed3'},
                Points{id=5, equ_id=1, high='1.1米', old='新建', lineType='null', items_id=1, note='备注信息：', mark='ZXG-5', sbbh='直线杆', sbzt='null', glsb='ZXG-3', lat='39.085848735588286', lon='117.09800257508161', weizhi='null', dangju=95.67, name='杆塔', latA='null', latB='null', lonA='null', lonB='null', category='null', equ='null', whether='0', batch='0', sblx='直线杆', uid='aea31c72-952c-4d18-a3cb-2044e2ba5f08'},
                Points{id=6, equ_id=23, high='米', old='新建', lineType='null', items_id=1, note='备注信息：', mark='DLGD-6', sbbh='电缆拐点', sbzt='null', glsb='', lat='39.086396416871736', lon='117.09800692798439', weizhi='null', dangju=0.0, name='地形点', latA='null', latB='null', lonA='null', lonB='null', category='null', equ='null', whether='1', batch='0', sblx='电缆拐点', uid='56d86ce9-d088-478a-8270-f4f65a41d80a'},
                Points{id=7, equ_id=0, high='米', old='新建', lineType='null', items_id=1, note='备注信息：', mark='null', sbbh='通讯线', sbzt='null', glsb='null', lat='39.08518309301188', lon='117.09772431264682', weizhi='null', dangju=0.0, name='地形点', latA='null', latB='null', lonA='null', lonB='null', category='null', equ='null', whether='1', batch='0', sblx='null', uid='c2620a86-8edd-435c-a661-d0fc1f45e494'}]

                [Points{id=1, equ_id=1, high='1.1米', old='新建', lineType='null', items_id=1, note='备注信息：', mark='ZXG-1', sbbh='直线杆', sbzt='null', glsb='null', lat='39.08604450703486', lon='117.09970602108335', weizhi='null', dangju=0.0, name='杆塔', latA='null', latB='null', lonA='null', lonB='null', category='null', equ='null', whether='0', batch='0', sblx='直线杆', uid='b66871e2-c842-420d-88de-1443cb6c528a'}]


*/
                //遍历所有的点的信息
                for (int i = 0, len = pointsList.size(); i < len; i++) {

                    //如果点的位置在当前屏幕内显示出来，如果不在不显示
                    /*  if (lngMin < Double.valueOf(pointsList.get(i).getLat()) && Double.valueOf(pointsList.get(i).getLat()) < lngMax && latMin < Double.valueOf(pointsList.get(i).getLon()) && Double.valueOf(pointsList.get(i).getLon()) < latMax) {*/
                    //添加覆盖物显示
                    try {
                        addMap(new LatLng(Double.valueOf(pointsList.get(i).getLat()), Double.valueOf(pointsList.get(i).getLon())), pointsList.get(i).getSblx(), pointsList.get(i).getId(), pointsList.get(i).getMark(), pointsList.get(i).getOld());
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }
                    try {
                        for (int j = 0, lens = pointsList.size(); j < lens; j++) {
                            if (pointsList.get(i).getGlsb() != null && pointsList.get(j).getMark() != null && pointsList.get(i).getGlsb().equals(pointsList.get(j).getMark())) {
                                latLngPolygon.clear();
                                latLngPolygon.add(new LatLng(Double.valueOf(pointsList.get(i).getLat()), Double.valueOf(pointsList.get(i).getLon())));
                                latLngPolygon.add(new LatLng(Double.valueOf(pointsList.get(j).getLat()), Double.valueOf(pointsList.get(j).getLon())));
                                //进行连线
                                assert latLngPolygon != null;
                                drawMyRoute(latLngPolygon, pointsList.get(j).getId(), pointsList.get(i).getId(), pointsList.get(i).getDangju());
                            }
                        }
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建ProrgressDialog
     */
    private void createProgressDialog() {
        context = this;
        mProgressDialog = new ProgressDialog(context);
        mProgressDialog.setMessage("加载数据中,请稍等...");
        mProgressDialog.show();
    }

    /**
     * 权限问题
     */
    private void showContacts() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
               /* || ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED*/) {
            //Toast.makeText(getApplicationContext(), "没有权限,请手动开启定位权限", Toast.LENGTH_SHORT).show();
            // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义）
            ActivityCompat.requestPermissions(MapActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_PHONE_STATE}, BAIDU_READ_PHONE_STATE);
        } else {
            initMap();
        }
    }

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        double x = sensorEvent.values[SensorManager.DATA_X];
        if (Math.abs(x - lastX) > 1.0) {
            mCurrentDirection = (int) x;
            locData = new MyLocationData.Builder()
                    .accuracy(mCurrentAccracy)
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(mCurrentDirection).latitude(mCurrentLat)
                    .longitude(mCurrentLon).build();
            if (mBaiduMap != null) {
                mBaiduMap.setMyLocationData(locData);
            }
        }
        lastX = x;
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {

    }

    @Override
    protected void onResume() {
        if (mMapView != null) {
            mMapView.onResume();
        }
        //创建ProgressDialog
        createProgressDialog();
        //启动线程
        ThreadManager.ThreadPool threadPool = getThreadPool();
        threadPool.execute(mRunnable);
        super.onResume();
        //为系统的方向传感器注册监听器
        mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
                SensorManager.SENSOR_DELAY_UI);

    }

    /**
     * 初始化界面
     */
    @SuppressLint("WrongViewCast")
    private void initView() {
        mMapBtnOne = findViewById(R.id.map_btn_one);
        mMapBtnOne.setOnClickListener(this);
        mMapBtnTwo = findViewById(R.id.map_btn_two);
        mMapBtnTwo.setOnClickListener(this);
        mMapBtnThree = findViewById(R.id.map_btn_three);
        mMapBtnThree.setOnClickListener(this);
        map_btn_length = findViewById(R.id.map_btn_length);
        map_btn_length.setOnClickListener(this);
        map_btn_model = findViewById(R.id.map_btn_model);
        map_btn_model.setOnClickListener(this);
        //覆盖物的点击事件
        markerOnclick();
        //线的点击事件
        try {
            polylineOnClick();
        } catch (Exception e) {
            e.printStackTrace();
        }
        location = findViewById(R.id.imageActionButton);
        location.setOnClickListener(v -> {
            LatLng lat = new LatLng(mCurrentLat, mCurrentLon);
            MapStatus mMapStatus = new MapStatus.Builder()
                    .target(lat)
                    .zoom(zoom)
                    .build();
            //定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
            MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);

            //改变地图状态
            mBaiduMap.animateMapStatus(mMapStatusUpdate);


        });

        ImageButton activity_ib_back = findViewById(R.id.activity_ib_back);
        activity_ib_back.setOnClickListener(this);
        TextView activity_tv_title = findViewById(R.id.activity_tv_title);
        activity_tv_save = findViewById(R.id.activity_tv_save);
        activity_tv_quxiao = findViewById(R.id.activity_tv_quxiao);
        activity_tv_title.setText(getString(R.string.title_kancha));
        activity_tv_quxiao.setVisibility(View.GONE);
        activity_tv_save.setVisibility(View.GONE);
        map_btn_four = findViewById(R.id.map_btn_four);
        iv_center = findViewById(R.id.iv_center);

        map_btn_name = findViewById(R.id.map_btn_name);
        map_btn_name.setOnClickListener(this);
        //TODO 点击如果关闭那么不进行连线。如果打开就进行连线。
        map_open_line = findViewById(R.id.map_open_line);
        map_open_line.setOnClickListener(this);

        //添加名字。TextView
        view = View.inflate(context, R.layout.activity_map_scenic_maker, null);
        // 填充数据
        map_marker = view.findViewById(R.id.map_marker);
        map_marker_image = view.findViewById(R.id.map_marker_image);
        ImageView map_iv_menu = findViewById(R.id.map_iv_menu);
        map_iv_menu.setOnClickListener(this);
        final List<Points> pointsList12 = MyApplication.getInstances().getPointsDao().queryBuilder().where(PointsDao.Properties.Whether.eq("1")).build().list();
        Log.e("allponts", pointsList12.toString());
    }

    private void polylineOnClick() {
        mBaiduMap.setOnPolylineClickListener(polyline -> {
            final Long aid, bid, line_id;
            final double lat_a, lat_b, lon_a, lon_b, length;
            Bundle bun = polyline.getExtraInfo();
            if (bun != null) {
                aid = bun.getLong("aid");
                bid = bun.getLong("bid");
                line_id = bun.getLong("line_id");
                lat_a = bun.getDouble("lat_a");
                lat_b = bun.getDouble("lat_b");
                lon_a = bun.getDouble("lon_a");
                lon_b = bun.getDouble("lon_b");
                length = bun.getDouble("length");
                View view = View.inflate(context, R.layout.activity_map_line_info, null);
                TextView xiugai = view.findViewById(R.id.map_tv_xiugai);
                TextView yidong = view.findViewById(R.id.map_tv_yidong);
                TextView shanchu = view.findViewById(R.id.map_tv_shanchu);
                TextView quxiao = view.findViewById(R.id.map_tv_quxiao);
                List<LatLng> latLngList = new ArrayList<>();
                latLngList.add(new LatLng(lat_a, lon_a));
                latLngList.add(new LatLng(lat_b, lon_b));
                final InfoWindow mInfoWindow = new InfoWindow(view, getLatLng(latLngList), -47);
                mBaiduMap.showInfoWindow(mInfoWindow);
                yidong.setText("插入");

                xiugai.setOnClickListener(v -> {
                    if (aid != 0 && bid != 0) {
                        Intent intent = new Intent(context, LineActivity.class);
                        intent.putExtra("aid", aid);
                        intent.putExtra("bid", bid);
                        intent.putExtra("cid", cid);
                        intent.putExtra("line_id", line_id);
                        startActivity(intent);
                    }
                    mBaiduMap.hideInfoWindow();
                });

                yidong.setOnClickListener(v -> {
                    if (aid != 0 && bid != 0) {
                        Intent intent = new Intent(context, DistanceActivity.class);
                        intent.putExtra("aid", aid);
                        intent.putExtra("bid", bid);
                        intent.putExtra("cid", cid);
                        intent.putExtra("length", length);
                        startActivityForResult(intent, 50);
                    }
                    mBaiduMap.hideInfoWindow();
                });

                shanchu.setOnClickListener(v -> {
                    mBaiduMap.hideInfoWindow();
                    final View views = View.inflate(context, R.layout.activity_map_dialog, null);
                    AlertDialog dialog = new AlertDialog.Builder(context).create();
                    dialog.setView(views);
                    dialog.show();
                    Button map_btn_quxiao = views.findViewById(R.id.map_btn_quxiao);
                    Button map_btn_queding = views.findViewById(R.id.map_btn_queding);
                    map_btn_queding.setOnClickListener(view12 -> {
                        dialog.dismiss();
                        polyline.remove();
                        Points points = MyApplication.getInstances().getPointsDao().queryBuilder().where(PointsDao.Properties.Id.eq(bid)).build().list().get(0);
                        points.setGlsb("");
                        MyApplication.getInstances().getPointsDao().update(points);
                    });

                    map_btn_quxiao.setOnClickListener(view1 -> dialog.dismiss());

                });

                quxiao.setOnClickListener(v -> mBaiduMap.hideInfoWindow());
            }
            return true;
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        initData();
    }

    /**
     * //TODO 删除
     * 覆盖物的点击事件
     */
    private void markerOnclick() {
        mBaiduMap.setOnMarkerClickListener(marker -> {

            View view = View.inflate(context, R.layout.activity_map_info, null);
            TextView xiugai = view.findViewById(R.id.map_tv_xiugai);
            TextView yidong = view.findViewById(R.id.map_tv_yidong);
            TextView shanchu = view.findViewById(R.id.map_tv_shanchu);
            TextView quxiao = view.findViewById(R.id.map_tv_quxiao);
            TextView kance = view.findViewById(R.id.map_tv_kance);
            final InfoWindow mInfoWindow = new InfoWindow(view, marker.getPosition(), -47);
            mBaiduMap.showInfoWindow(mInfoWindow);
            kance.setOnClickListener(v -> {
                mBaiduMap.hideInfoWindow();
                jixukance = true;
                jid = Long.valueOf(marker.getTitle());
                jpoints = MyApplication.getInstances().getPointsDao().queryBuilder().where(PointsDao.Properties.Id.eq(jid)).build().list().get(0);
            });
            xiugai.setOnClickListener(v -> {
                mBaiduMap.hideInfoWindow();
                Intent intent = new Intent(context, EquActivity.class);
                if (marker.getTitle() != null) {
                    intent.putExtra("is", "0");
                    intent.putExtra("cid", Long.parseLong(marker.getTitle()));
                    bid = Long.parseLong(marker.getTitle());
                    zid = cid;
                    intent.putExtra("id", cid);
                }
                startActivity(intent);
            });
            yidong.setOnClickListener(v -> {
                mBaiduMap.hideInfoWindow();
                jixukance = true;
                jid = Long.valueOf(marker.getTitle());
                jpoints = MyApplication.getInstances().getPointsDao().queryBuilder().where(PointsDao.Properties.Id.eq(jid)).build().list().get(0);
                activity_tv_quxiao.setVisibility(View.VISIBLE);
                activity_tv_save.setVisibility(View.VISIBLE);
                MARKER_DEFINE = true;
                final Points points = MyApplication.getInstances().getPointsDao().queryBuilder().where(PointsDao.Properties.Id.eq(Long.parseLong(marker.getTitle()))).build().list().get(0);
                LatLng lat = new LatLng(Double.valueOf(points.getLat()), Double.valueOf(points.getLon()));
                MapStatus mMapStatus = new MapStatus.Builder().target(lat).zoom(19).build();
                //定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
                MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
                //改变地图状态
                mBaiduMap.animateMapStatus(mMapStatusUpdate);

                iv_center.setBackgroundResource(R.drawable.define_blue);

                mMapBtnOne.setVisibility(View.GONE);
                mMapBtnTwo.setVisibility(View.GONE);
                mMapBtnThree.setVisibility(View.GONE);
                switch (points.getName()) {
                    case "通讯线":
                        map_btn_four.setBackgroundResource(R.drawable.dixingdian1);
                        map_btn_four.setVisibility(View.VISIBLE);
                        break;
                    case "杆塔":
                        map_btn_four.setBackgroundResource(R.drawable.ganta1);
                        map_btn_four.setVisibility(View.VISIBLE);
                        break;
                    default:
                        map_btn_four.setBackgroundResource(R.drawable.shebie1);
                        map_btn_four.setVisibility(View.VISIBLE);
                        break;
                }

                mMapBtnOne.setEnabled(false);
                mMapBtnTwo.setEnabled(false);
                mMapBtnThree.setEnabled(false);

                //点击取消时的操作
                activity_tv_quxiao.setOnClickListener(v1 -> {
                    MARKER_DEFINE = false;
                    iv_center.setBackgroundResource(R.drawable.define_green);
                    map_btn_four.setVisibility(View.GONE);
                    activity_tv_quxiao.setVisibility(View.GONE);
                    activity_tv_save.setVisibility(View.GONE);
                    mMapBtnOne.setVisibility(View.VISIBLE);
                    mMapBtnTwo.setVisibility(View.VISIBLE);
                    mMapBtnThree.setVisibility(View.VISIBLE);
                    mMapBtnOne.setEnabled(true);
                    mMapBtnTwo.setEnabled(true);
                    mMapBtnThree.setEnabled(true);
                });

                //点击确定时的操作
                activity_tv_save.setOnClickListener(v12 -> {
                    MARKER_DEFINE = false;
                    iv_center.setBackgroundResource(R.drawable.define_green);
                    map_btn_four.setVisibility(View.GONE);
                    activity_tv_quxiao.setVisibility(View.GONE);
                    activity_tv_save.setVisibility(View.GONE);
                    mMapBtnOne.setVisibility(View.VISIBLE);
                    mMapBtnTwo.setVisibility(View.VISIBLE);
                    mMapBtnThree.setVisibility(View.VISIBLE);
                    mMapBtnOne.setEnabled(true);
                    mMapBtnTwo.setEnabled(true);
                    mMapBtnThree.setEnabled(true);


                    points.setLat(lc.latitude + "");
                    points.setLon(lc.longitude + "");
                    MyApplication.getInstances().getPointsDao().update(points);
                    marker.setPosition(new LatLng(lc.latitude, lc.longitude));

                    try {
                        Line line = MyApplication.getInstances().getLineDao().queryBuilder().where(LineDao.Properties.Start_id.eq(points.getUid())).build().list().get(0);

                        line.setLatA(lc.latitude + "");
                        line.setLonA(lc.longitude + "");
                        MyApplication.getInstances().getLineDao().update(line);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    initData();
                    MyUtils.getToast(context, "移动成功");
                });
            });
            shanchu.setOnClickListener(v -> {
                mBaiduMap.hideInfoWindow();
                final View views = View.inflate(context, R.layout.activity_map_dialog, null);
                AlertDialog dialog = new AlertDialog.Builder(context).create();
                dialog.setView(views);
                dialog.show();
                Button map_btn_quxiao = views.findViewById(R.id.map_btn_quxiao);
                Button map_btn_queding = views.findViewById(R.id.map_btn_queding);
                map_btn_queding.setOnClickListener(view12 -> {
                    dialog.dismiss();

                    try {
                        //删除数据库中点的信息
                        Points points = MyApplication.getInstances().getPointsDao().queryBuilder().where(PointsDao.Properties.Id.eq(Long.parseLong(marker.getTitle()))).build().list().get(0);
                        MyApplication.getInstances().getPointsDao().deleteByKey(Long.parseLong(marker.getTitle()));

                        Line line = null;
                        if (points.getGlsb() != null) {
                            try {
                                line = MyApplication.getInstances().getLineDao().queryBuilder().where(LineDao.Properties.End_id.eq(points.getGlsb())).build().list().get(0);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        if (line != null)
                            MyApplication.getInstances().getLineDao().delete(line);
                        marker.remove();
                        initData();
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }
                });
                map_btn_quxiao.setOnClickListener(view1 -> dialog.dismiss());

            });
            quxiao.setOnClickListener(v -> mBaiduMap.hideInfoWindow());

            return false;
        });
    }


    //Android6.0申请权限的回调方法
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            // requestCode即所声明的权限获取码，在checkSelfPermission时传入
            case BAIDU_READ_PHONE_STATE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获取到权限，作相应处理（调用定位SDK应当确保相关权限均被授权，否则可能引起定位失败）
                    initMap();
                } else {
                    // 没有获取到权限，做特殊处理
                    //Toast.makeText(getApplicationContext(), "获取位置权限失败，请手动开启", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }

    /**
     * 按钮的点击事件
     */
    @SuppressLint({"WrongConstant", "SetTextI18n"})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //TODO 地形点
            case R.id.map_btn_one:
                //屏幕下方通讯线的按钮
                if (lc != null) {
                    addInitMaps(new LatLng(lc.latitude, lc.longitude));
                } else
                    MyUtils.getToast(context, getString(R.string.map_huoqu));
                break;
            case R.id.map_btn_two:
                //屏幕下方杆塔的按钮
                if (lc != null) {
                    addInitMap(new LatLng(lc.latitude, lc.longitude), "杆塔");
                } else
                    MyUtils.getToast(context, getString(R.string.map_huoqu));
                break;
            case R.id.map_btn_three:
                //屏幕下方设备的按钮
                if (lc != null) {
                    addInitMap(new LatLng(lc.latitude, lc.longitude), "设备");
                } else
                    MyUtils.getToast(context, getString(R.string.map_huoqu));
                break;
            case R.id.map_btn_length:
                //是否显示档距
                if (!btn_Length_isCheck) {
                    btn_Length_isCheck = true;
                    map_btn_length.setBackgroundResource(R.drawable.guanbidangju);
                    initData();

                } else {
                    btn_Length_isCheck = false;
                    map_btn_length.setBackgroundResource(R.drawable.dakaidangju);
                    mBaiduMap.clear();
                    initData();
                }
                break;
            case R.id.map_btn_model:
                //卫星模式/拖动模式
                if (!btn_model) {
                    btn_model = true;

                    map_btn_model.setBackgroundResource(R.drawable.weixingmoshi);
                    mBaiduMap.getUiSettings().setZoomGesturesEnabled(false);
                    LatLng lat = new LatLng(mCurrentLat, mCurrentLon);
                    MapStatus mMapStatus = new MapStatus.Builder()
                            .target(lat)
                            .zoom(19)
                            .build();
                    //定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
                    MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
                    //改变地图状态
                    mBaiduMap.animateMapStatus(mMapStatusUpdate);
                    mCurrentMode = MyLocationConfiguration.LocationMode.FOLLOWING;//定位跟随态
                    mBaiduMap.getUiSettings().setScrollGesturesEnabled(false);
                } else {
                    btn_model = false;
                    map_btn_model.setBackgroundResource(R.drawable.tuodongmoshi);
                    //禁止拖拽
                    mBaiduMap.getUiSettings().setScrollGesturesEnabled(true);
                    //禁止双击操作
                    mBaiduMap.getUiSettings().setZoomGesturesEnabled(true);
                }

                break;
            case R.id.activity_ib_back:
                //返回按钮
                startActivity(new Intent(context, BottomActivity.class));
                finish();
                break;
            case R.id.map_iv_menu:
                setMenu();
                break;
            case R.id.map_btn_name:
                //是否显示名称
                if (!btn_Name_isCheck) {
                    btn_Name_isCheck = true;
                    map_btn_name.setBackgroundResource(R.drawable.pingbimingcheng);
                    mBaiduMap.clear();
                    initData();
                } else {
                    btn_Name_isCheck = false;
                    map_btn_name.setBackgroundResource(R.drawable.xianshimingcheng);
                    mBaiduMap.clear();
                    initData();
                }
                break;
            //TODO 跟新部分
            case R.id.map_open_line:
                isOpenOrClose = !isOpenOrClose;
                setMapData();
                break;
        }
    }

    /**
     * 添加地形点
     *
     * @param latLng 位置信息
     */
    @SuppressLint("SetTextI18n")
    private void addInitMaps(LatLng latLng) {
        bottomSheetDialog = new BottomSheetDialog(this);
        bottomSheetDialog.setContentView(R.layout.activity_map_bottom_dixing);
        maps_ed_address = bottomSheetDialog.findViewById(R.id.maps_ed_address);
        maps_ed_name = bottomSheetDialog.findViewById(R.id.maps_ed_name);
        maps_sp_type = bottomSheetDialog.findViewById(R.id.maps_sp_type);
        maps_ed_length = bottomSheetDialog.findViewById(R.id.maps_ed_length);
        maps_ed_width = bottomSheetDialog.findViewById(R.id.maps_ed_width);
        maps_tv_location = bottomSheetDialog.findViewById(R.id.maps_tv_location);
        maps_ed_high = bottomSheetDialog.findViewById(R.id.maps_ed_high);
        maps_ed_note = bottomSheetDialog.findViewById(R.id.maps_ed_note);
        maps_btn_cancel = bottomSheetDialog.findViewById(R.id.maps_btn_cancel);
        maps_btn_add = bottomSheetDialog.findViewById(R.id.maps_btn_add);
        maps_rl_add = bottomSheetDialog.findViewById(R.id.maps_rl_add);
        bottomSheetDialog.show();
        final List<Equip> equips = getEquIp(4);
        List<String> adapter_dataq = new ArrayList<>();
        for (int i = 0, len = equips.size(); i < len; i++) {
            if (equips.get(i).getName().contains("拐点")) {
                adapter_dataq.add(0, equips.get(i).getName());
                equipList.set(0, equips.get(i));
            } else {
                adapter_dataq.add(equips.get(i).getName());
                equipList.add(equips.get(i));
            }
        }
        maps_tv_location.setText(latLng.latitude + "、" + latLng.longitude);
        //适配器
        ArrayAdapter<String> arr_adapterq = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, adapter_dataq);
        //设置样式
        arr_adapterq.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        maps_sp_type.setAdapter(arr_adapterq);
        maps_sp_type.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (maps_sp_type.getSelectedItem().toString().trim().equals(equips.get(position).getName())) {
                    if (pointsList.size() > 0) {
                        Long mid = pointsList.get(pointsList.size() - 1).getId() + 1;
                        maps_ed_name.setText(equips.get(position).getCode() + "-" + mid);
                    } else {
                        maps_ed_name.setText(equips.get(position).getCode() + "-" + 1);
                    }
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });


        //TODO 点击完成时保存点的信息
        maps_btn_add.setOnClickListener(v -> {
            /*if (!maps_ed_length.getText().toString().equals("") && !maps_ed_width.getText().toString().equals("") && !maps_ed_high.getText().toString().equals("")) {*/
            //map_rl_add.setVisibility(View.GONE);
            if (!btn_model) {
                mBaiduMap.getUiSettings().setZoomGesturesEnabled(false);
            } else {
                mBaiduMap.getUiSettings().setZoomGesturesEnabled(true);
            }
            mBaiduMap.getUiSettings().setScrollGesturesEnabled(true);
            double lengths = 0;
            Points points = new Points();
            points.setId(null);
            UUID uuid = UUID.randomUUID();
            points.setUid(uuid + "");
            points.setItems_id(cid);
            points.setName("地形点");
            points.setNote("备注信息：" + maps_ed_note.getText().toString().trim());
            points.setLat(latLng.latitude + "");
            points.setLon(latLng.longitude + "");
            points.setBatch("0");
            Log.e("equipList",equipList.toString());
            /**[Equip{id=23, name='电缆拐点', code='DLGD'},
             *  Equip{id=14, name='高低压线', code='GDYX'},
                Equip{id=15, name='道路', code='DLDXD'},
                Equip{id=16, name='河流', code='HLDXD'},
                Equip{id=17, name='建筑物', code='JZWDXD'}]
             */
            for (int i = 0, len = equipList.size(); i < len; i++) {
                if (maps_sp_type.getSelectedItem().toString().trim().equals(equipList.get(i).getName())) {
                    points.setEqu_id(equipList.get(i).getId());
                    points.setSblx(equipList.get(i).getName());
                    List<Points> pointsList1 = MyApplication.getInstances().getPointsDao().queryBuilder().build().list();
                    //TODO 这里搞所有的地形点。
                    Log.e("first=",pointsList1.toString());
                    if (pointsList1.size() > 0) {
                        //TODO 循环所有的地形点。
                        for(int j = pointsList1.size()-1;j>=pointsList1.size(); j--) {
                            //TODO 如果最后一个点是地形点里面的拐点那么这里设置关联关系和mark  而且之前点最端点不是地形点除过拐点的
                            if (maps_sp_type.getSelectedItem().toString().trim().contains("拐点")&&(pointsList1.get(pointsList1.size() - 1).getEqu_id()!=4||pointsList1.get(pointsList1.size() - 1).getSblx().contains("拐点"))){//TODO  拐点地形点
                               Long mid = pointsList1.get(pointsList1.size() - 1).getId() + 1;
                               //TODO 这里获取最后一个点的
                               getEquIp( pointsList1.get(pointsList1.size() - 1).getEqu_id());
                               //TODO 获取最后一个点的关联关系。
                               Log.e("first拐点地形点=",pointsList1.get(pointsList1.size() - 1).toString());
                               points.setMark(getEquIp( pointsList1.get(pointsList1.size() - 1).getEqu_id()).get(j).getCode() + "-" + mid);
                               points.setGlsb(pointsList1.get(j).getMark());
                           }else{//TODO 其他地形点
                               Log.e("first其他地形点=",pointsList1.toString());
                               Long mid = pointsList1.get(pointsList1.size() - 1).getId() + 1;
                               //TODO 这里获取最后一个点的
                               points.setMark(equips.get(i).getCode() + "-" + mid);
                               points.setGlsb("");


                           }
                        }

                    } else {
                        points.setMark(equipList.get(i).getCode() + "-" + 1);
                    }

                }
            }
            if (high != 0) {
                points.setHigh(maps_ed_high.getText().toString() + "米");
            } else {
                points.setHigh("");
            }

            if (maps_ed_address.getText().toString().equals("")) {
                points.setAddress("");
            } else {
                points.setAddress(maps_ed_address.getText().toString());
            }

            points.setLength(maps_ed_length.getText().toString() + "米");
            points.setWidth(maps_ed_width.getText().toString() + "米");
            points.setName("地形点");
            points.setSbbh(maps_sp_type.getSelectedItem().toString().trim());
            //TODO 关联关系
            //TODO Whether是否为地形点 1代表是地形点吧但是这里如果是地形拐点就需要搞定为0
            if (points.getName().contains("拐点")) {
                points.setWhether("0");
            } else {
                points.setWhether("1");

            }
            points.setDangju(lengths);
            points.setOld("新建");
            MyApplication.getInstances().getPointsDao().insert(points);
            //添加marker
            addMap(latLng, points.getSblx(), points.getId(), points.getMark(), "新建");
            //TODO 拐点连线代码部分 这里如果是拐点进行连线 开始部分

            //添加marker时添加线
            initDatasPoints();
            List<Points> list;
            //final List<Points> pointsList12 = MyApplication.getInstances().getPointsDao().queryBuilder().where(PointsDao.Properties.Items_id.eq(cid), PointsDao.Properties.Whether.eq("1"), PointsDao.Properties.Batch.eq("0")).build().list();
            final List<Points> pointsList12 = MyApplication.getInstances().getPointsDao().queryBuilder().where(PointsDao.Properties.Whether.eq("1")).build().list();
            Log.e("allponts", pointsList12.toString());

            /**
             Points{id=2, equ_id=1, high='1.1米', old='新建', lineType='null', items_id=1, note='备注信息：', mark='ZXG-2', sbbh='直线杆', sbzt='null', glsb='ZXG-1', lat='39.08610320177811', lon='117.09976908991655', weizhi='null', dangju=64.17, name='杆塔', latA='null', latB='null', lonA='null', lonB='null', category='null', equ='null', whether='0', batch='0', sblx='直线杆', uid='0267cbc2-e2da-4f2e-af47-dcf378baf44f'},
             Points{id=3, equ_id=1, high='1.1米', old='新建', lineType='null', items_id=1, note='备注信息：', mark='ZXG-3', sbbh='直线杆', sbzt='null', glsb='ZXG-2', lat='39.08569273425972', lon='117.0990925409082', weizhi='null', dangju=74.12, name='杆塔', latA='null', latB='null', lonA='null', lonB='null', category='null', equ='null', whether='0', batch='0', sblx='直线杆', uid='bbf6722d-2991-4567-aeca-eacbc28c0f68'}]
             [Points{id=1, equ_id=1, high='1.1米', old='新建', lineType='null', items_id=1, note='备注信息：', mark='ZXG-1', sbbh='直线杆', sbzt='null', glsb='null', lat='39.08646762710225', lon='117.09919261745164', weizhi='null', dangju=0.0, name='杆塔', latA='null', latB='null', lonA='null', lonB='null', category='null', equ='null', whether='0', batch='0', sblx='直线杆', uid='6fbf99dd-e73b-469c-ac24-352be48f76ca'},
             Points{id=2, equ_id=1, high='1.1米', old='新建', lineType='null', items_id=1, note='备注信息：', mark='ZXG-2', sbbh='直线杆', sbzt='null', glsb='ZXG-1', lat='39.08610320177811', lon='117.09976908991655', weizhi='null', dangju=64.17, name='杆塔', latA='null', latB='null', lonA='null', lonB='null', category='null', equ='null', whether='0', batch='0', sblx='直线杆', uid='0267cbc2-e2da-4f2e-af47-dcf378baf44f'},
             Points{id=3, equ_id=1, high='1.1米', old='新建', lineType='null', items_id=1, note='备注信息：', mark='ZXG-3', sbbh='直线杆', sbzt='null', glsb='ZXG-2', lat='39.08569273425972', lon='117.0990925409082', weizhi='null', dangju=74.12, name='杆塔', latA='null', latB='null', lonA='null', lonB='null', category='null', equ='null', whether='0', batch='0', sblx='直线杆', uid='bbf6722d-2991-4567-aeca-eacbc28c0f68'},
             Points{id=5, equ_id=1, high='1.1米', old='新建', lineType='null', items_id=1, note='备注信息：', mark='ZXG-5', sbbh='直线杆', sbzt='null', glsb='ZXG-3', lat='39.085848735588286', lon='117.09800257508161', weizhi='null', dangju=95.67, name='杆塔', latA='null', latB='null', lonA='null', lonB='null', category='null', equ='null', whether='0', batch='0', sblx='直线杆', uid='aea31c72-952c-4d18-a3cb-2044e2ba5f08'}]
             [Points{id=4, equ_id=23, high='13米', old='新建', lineType='null', items_id=1, note='备注信息：', mark='DLGD-4', sbbh='电缆拐点', sbzt='null', glsb='', lat='39.086099683063175', lon='117.09854864668418', weizhi='null', dangju=0.0, name='地形点', latA='null', latB='null', lonA='null', lonB='null', category='null', equ='null', whether='1', batch='0', sblx='电缆拐点', uid='f3bdb82e-5098-4c99-991d-b321bd24eed3'},
             Points{id=6, equ_id=23, high='米', old='新建', lineType='null', items_id=1, note='备注信息：', mark='DLGD-6', sbbh='电缆拐点', sbzt='null', glsb='', lat='39.086396416871736', lon='117.09800692798439', weizhi='null', dangju=0.0, name='地形点', latA='null', latB='null', lonA='null', lonB='null', category='null', equ='null', whether='1', batch='0', sblx='电缆拐点', uid='56d86ce9-d088-478a-8270-f4f65a41d80a'}]
             */

            List<LatLng> latLngList = new ArrayList<>();
            if (pointsList12.size() > 0)
                latLngList.add(new LatLng(Double.valueOf(pointsList12.get(pointsList12.size() - 1).getLat()), Double.valueOf(pointsList12.get(pointsList12.size() - 1).getLon())));
            if (pointsList12.size() > 1) {
                //TODO 这里获取通过满足多个条件的点。   mark=Glsb
                list = MyApplication.getInstances().getPointsDao().queryBuilder().where(PointsDao.Properties.Mark.eq(pointsList12.get(pointsList12.size() - 1).getGlsb())).build().list();
                if (list.size() > 0) {
                    latLngList.add(new LatLng(Double.valueOf(list.get(0).getLat()), Double.valueOf(list.get(0).getLon())));
                }
            }

            if (latLngList.size() > 1)
                //TODO 线 去添加线
                drawMyRoute(latLngList, pointsList12.get(pointsList12.size() - 2).getId(), pointsList12.get(pointsList12.size() - 1).getId(), lengths);


            //TODO 点之间连线结束部分
            bottomSheetDialog.dismiss();

        });
        maps_btn_cancel.setOnClickListener(view -> {
            if (!btn_model) {
                mBaiduMap.getUiSettings().setZoomGesturesEnabled(false);
            } else {
                mBaiduMap.getUiSettings().setZoomGesturesEnabled(true);
            }
            mBaiduMap.getUiSettings().setScrollGesturesEnabled(true);
            bottomSheetDialog.dismiss();
        });

    }

    /**
     * 画线
     */
    @SuppressLint("SetTextI18n")
    private void drawMyRoute(List<LatLng> points2, Long aid, Long bid, double lengths) {
        Points points = MyApplication.getInstances().getPointsDao().queryBuilder().where(PointsDao.Properties.Id.eq(bid)).build().list().get(0);
        Line line = null;

        if (points.getUid() != null) {
            try {
                line = MyApplication.getInstances().getLineDao().queryBuilder().where(LineDao.Properties.Start_id.eq(points.getUid())).build().list().get(0);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        Bundle bundle = new Bundle();
        bundle.putLong("aid", aid);
        bundle.putLong("bid", bid);
        bundle.putDouble("lat_a", points2.get(0).latitude);
        bundle.putDouble("lon_a", points2.get(0).longitude);
        bundle.putDouble("lat_b", points2.get(1).latitude);
        bundle.putDouble("lon_b", points2.get(1).longitude);
        bundle.putDouble("length", lengths);
        assert line != null;
        try {
            bundle.putLong("line_id", line.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            OverlayOptions ooPolyline;
            if (line.getType_Id().equals("11") || line.getType_Id().equals("28") || line.getType_Id().equals("29")) {
                ooPolyline = new PolylineOptions()
                        .width(3)
                        .color(Color.BLACK)
                        .points(points2)
                        .extraInfo(bundle);

            } else {
                ooPolyline = new PolylineOptions()
                        .width(3)
                        .color(Color.BLACK)
                        .dottedLine(true)
                        .points(points2)
                        .extraInfo(bundle);
            }
            mBaiduMap.addOverlay(ooPolyline);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (btn_Length_isCheck) {
            LatLng lng1 = new LatLng(points2.get(0).latitude, points2.get(0).longitude);
            LatLng lng2 = new LatLng(points2.get(1).latitude, points2.get(1).longitude);
            double aaa, bbb;
            if (lng1.longitude > lng2.longitude) {
                aaa = (lng1.longitude - lng2.longitude) / 2 + lng2.longitude;
            } else {
                aaa = (lng2.longitude - lng1.longitude) / 2 + lng1.longitude;
            }

            if (lng1.latitude > lng2.latitude) {
                bbb = (lng1.latitude - lng2.latitude) / 2 + lng2.latitude;
            } else {
                bbb = (lng2.latitude - lng1.latitude) / 2 + lng1.latitude;
            }

            LatLng latLng = new LatLng(bbb, aaa);

            OverlayOptions option;
            if (densityDpi > 320) {
                option = new TextOptions()
                        .position(latLng)
                        .text(lengths + "米")
                        .zIndex(9)
                        .fontColor(Color.rgb(51, 51, 51))
                        .fontSize(35);
            } else {
                option = new TextOptions()
                        .position(latLng)
                        .text(lengths + "米")
                        .zIndex(9)
                        .fontColor(Color.rgb(51, 51, 51))
                        .fontSize(24);
            }
            //.rotate()旋转，其实可以实现。;
            //添加marker
            mBaiduMap.addOverlay(option);
        }
    }

    /**
     * 设置头部下拉菜单栏
     */
    private void setMenu() {
        String[] abs;
        if (state.equals("在线")) {
            abs = new String[]{"模式切换", "显示所有", "更新项目", "3D/2D切换", "结束勘测"};
        } else {
            abs = new String[]{"模式切换", "显示所有", "一键刷新", "3D/2D切换", "结束勘测"};
        }
        PopupMenu popupMenu = new PopupMenu(this, abs);
        popupMenu.showLocation(R.id.map_iv_menu);
        popupMenu.setOnItemClickListener((item, str) -> {
            switch (str) {
                case "模式切换": {
                    popupMenu.dismiss();
                    String[] stringItems = {"卫星模式", "空白模式", "普通模式"};
                    final ActionSheetDialog dialog = new ActionSheetDialog(this, stringItems, null);
                    dialog.isTitleShow(false).show();
                    dialog.setOnOperItemClickL((parent, view, position, id) -> {
                        switch (position) {
                            case 0:
                                mBaiduMap.setMapType(BaiduMap.MAP_TYPE_SATELLITE);
                                //map_btn_change.setBackgroundResource(R.drawable.weixingmoshi);
                                dialog.dismiss();
                                break;
                            case 1:
                                mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NONE);
                                //map_btn_change.setBackgroundResource(R.drawable.kongbaimoshi);
                                dialog.dismiss();
                                break;
                            case 2:
                                mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
                                //map_btn_change.setBackgroundResource(R.drawable.putongmoshi);
                                dialog.dismiss();
                                break;
                        }
                    });
                    break;
                }
                case "显示所有": {
                    popupMenu.dismiss();
                    final List<LatLng> points = new ArrayList<>();
                    if (pointsList != null && pointsList.size() > 0) {
                        for (int i = 0; i < pointsList.size(); i++) {
                            points.add(new LatLng(Double.valueOf(pointsList.get(i).getLat()), Double.valueOf(pointsList.get(i).getLon())));
                        }

                        LatLngBounds.Builder builder1 = new LatLngBounds.Builder();
                        for (LatLng p : points) {
                            builder1 = builder1.include(p);
                        }
                        LatLngBounds latlngBounds = builder1.build();
                        /*MapStatusUpdate u = MapStatusUpdateFactory.newLatLngBounds(latlngBounds, mMapView.getWidth(), mMapView.getHeight());*/
                        MapStatusUpdate us = MapStatusUpdateFactory.newLatLngBounds(builder1.build());
                        MapStatusUpdateFactory.newLatLngBounds(latlngBounds, mMapView.getWidth(), mMapView.getHeight());
                        mBaiduMap.animateMapStatus(us);

                    }
                    break;
                }
                case "一键刷新": {
                    popupMenu.dismiss();
                    initData();
                    break;
                }
                case "更新项目": {
                    popupMenu.dismiss();
                    //创建ProgressDialog
                    createProgressDialog();
                    //启动线程
                    ThreadManager.ThreadPool threadPool = getThreadPool();
                    threadPool.execute(mRunnable1);

                    break;
                }
                case "3D/2D切换": {
                    popupMenu.dismiss();
                    String[] stringItem = {"3D模式", "2D模式"};
                    final ActionSheetDialog dialogs = new ActionSheetDialog(this, stringItem, null);
                    dialogs.isTitleShow(false).show();
                    dialogs.setOnOperItemClickL((parent, view, position, id) -> {
                        switch (position) {
                            case 0:
                                mBaiduMap.setBuildingsEnabled(true);
                                mBaiduMap.getUiSettings().setOverlookingGesturesEnabled(true);
                                mBaiduMap.getUiSettings().setRotateGesturesEnabled(true);
                                //map_btn_mode.setText("3D");
                                dialogs.dismiss();
                                break;
                            case 1:
                                mBaiduMap.setBuildingsEnabled(false);
                                mBaiduMap.getUiSettings().setOverlookingGesturesEnabled(false);
                                mBaiduMap.getUiSettings().setRotateGesturesEnabled(false);
                                //.setText("2D");
                                dialogs.dismiss();
                                break;
                        }
                    });
                    break;
                }
                case "结束勘测": {
                    popupMenu.dismiss();
                    setStop();
                    break;
                }
            }
        });
    }

    /**
     * 结束勘察
     */
    private void setStop() {
        if ("在线".equals(state)) {
            final NormalDialog dialog = new NormalDialog(context);
            dialog.content("是否要结束本项目的勘察(此操作不可返回)?")//
                    .style(NormalDialog.STYLE_TWO)//
                    .btnNum(2)
                    .title("结束勘察")
                    .btnText("取消", "确定")//
                    .show();
            dialog.setOnBtnClickL(
                    dialog::dismiss, () -> {
                        dialog.dismiss();
                        try {
                            if (MyApplication.getInstances().IsLogin()) {
                                if (NetworkUtils.isConnected()) {
                                    if (GetToken.getInstance().getToken()) {
                                        stop();
                                    } else {
                                        GetToken.getInstance().setToken();
                                        stop();
                                    }
                                } else {
                                    ToastUtils.showShort("网络无连接");
                                }
                            } else {
                                ToastUtils.showShort("当前未登录");
                            }
                            finish();
                        } catch (Exception e) {
                            e.printStackTrace();
                            ToastUtils.showShort("结束勘察失败");
                        }
                    });

        } else {
            ToastUtils.showShort("本地项目没有结束勘测");
        }
    }

    /**
     * 调取结束勘测接口
     */
    private void stop() {
        LinkedHashMap<String, Object> map = new LinkedHashMap<>();
        @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DATE, 0);
        Date monday = c.getTime();
        String preMonday = sdf.format(monday);
        map.put("surverytaskid", items.getProjectId());
        map.put("finishtime", preMonday);
        String result = HttpConfig.callService("taskxckctime", map);


        if (parseXMLWithPull(result)) {
            ToastUtils.showShort("上传时间成功");
        } else {
            ToastUtils.showShort("上传时间失败");
        }
        startActivity(new Intent(context, BottomActivity.class));
    }

    /**
     * @param str 查询的序号
     * @return Equip
     */
    public List<Equip> getEquIp(int str) {
        List<Equip> strings = null;
        try {
            strings = new ArrayList<>();
            SQLiteDatabase db = openDatabase(context);
            assert db != null;
            @SuppressLint("Recycle") Cursor cursor = db.rawQuery("select * from EquipType where component=" + str, null);//此处的db是表名，name是列名
            while (cursor.moveToNext()) {
                Equip equip = new Equip();
                equip.setId(cursor.getInt(0));
                equip.setName(cursor.getString(1));
                equip.setCode(cursor.getString(4));
                strings.add(equip);
            }
            cursor.close();
            db.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strings;
    }

    /**
     * 点击添加按钮时，保存到数据库。
     *
     * @param latLng 位置信息
     * @param name   名称
     */
    @SuppressLint("SetTextI18n")
    private void addInitMap(final LatLng latLng, final String name) {
        bottomSheetDialog = new BottomSheetDialog(this);
        bottomSheetDialog.setContentView(R.layout.activity_map_bottom);
        map_btn_add = bottomSheetDialog.findViewById(R.id.map_btn_add);
        //map_rl_add = findViewById(R.id.map_rl_add);
        //String [] mStringArray=getResources().getStringArray(R.array.state);
        map_sp_state = bottomSheetDialog.findViewById(R.id.map_sp_state);
        /*TestArrayAdapter mAdapter = new TestArrayAdapter(this,mStringArray);
        map_sp_state.setAdapter(mAdapter);*/
        map_tv_location = bottomSheetDialog.findViewById(R.id.map_tv_location);
        map_ed_name = bottomSheetDialog.findViewById(R.id.map_ed_name);
        map_sp_sort = bottomSheetDialog.findViewById(R.id.map_sp_sort);
        map_sp_type = bottomSheetDialog.findViewById(R.id.map_sp_type);
        map_tv_name = bottomSheetDialog.findViewById(R.id.map_tv_name);
        map_tv_dixing_sort = bottomSheetDialog.findViewById(R.id.map_tv_dixing_sort);
        map_sp_dixing_sort = bottomSheetDialog.findViewById(R.id.map_sp_dixing_sort);
        map_ll_dixing_sort = bottomSheetDialog.findViewById(R.id.map_ll_dixing_sort);
        map_ed_note = bottomSheetDialog.findViewById(R.id.map_ed_note);
        map_sp_equ = bottomSheetDialog.findViewById(R.id.map_sp_equ);
        map_ed_high = bottomSheetDialog.findViewById(R.id.map_ed_high);
        map_ll_lijiu = bottomSheetDialog.findViewById(R.id.map_ll_lijiu);
        map_ll_guanlian = bottomSheetDialog.findViewById(R.id.map_ll_guanlian);

        map_ll_guanlian.setVisibility(View.VISIBLE);
        map_ll_lijiu.setVisibility(View.VISIBLE);

        List<String> adapter_data = new ArrayList<>();
        for (int i = 0, len = pointsList.size(); i < len; i++) {
            if (!pointsList.get(i).getMark().contains("DX"))
                adapter_data.add(pointsList.get(i).getMark());
        }
        //适配器
        ArrayAdapter<String> arr_adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, adapter_data);
        //设置样式
        arr_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        map_sp_equ.setAdapter(arr_adapter);
        final List<Points> pointsList = MyApplication.getInstances().getPointsDao().queryBuilder().where(PointsDao.Properties.Items_id.eq(cid), PointsDao.Properties.Whether.eq("0"), PointsDao.Properties.Batch.eq("0")).build().list();

        if (pointsList.size() > 0) {
            if (!pointsList.get(pointsList.size() - 1).getName().equals("通讯线")) {
                if (jixukance) {
                    glsb = jpoints.getMark();
                    uid = jpoints.getUid();
                } else
                    glsb = pointsList.get(pointsList.size() - 1).getMark();
                uid = pointsList.get(pointsList.size() - 1).getUid();
            } else {
                glsb = "";
                uid = pointsList.get(pointsList.size() - 1).getUid();
            }
        }
        //根据值, 设置spinner默认选中:
        setSpinnerItemSelectedByValue(map_sp_equ, glsb);

        mBaiduMap.getUiSettings().setScrollGesturesEnabled(false);
        mBaiduMap.getUiSettings().setZoomGesturesEnabled(false);
        //map_rl_add.setVisibility(View.VISIBLE);
        map_tv_location.setText(latLng.latitude + "、" + latLng.longitude);
        map_ed_high.setText(high + "米");
        map_tv_name.setText(name + "");
        if (!map_ed_note.getText().toString().equals("")) {
            map_ed_note.setText("");
            map_ed_name.setText("");
        }
        switch (name) {
            case "杆塔":
                final List<Equip> equip = getEquIp(1);
                map_sp_sort.setText("杆塔");
                List<String> adapter_data1 = new ArrayList<>();
                for (int i = 0, len = equip.size(); i < len; i++) {
                    adapter_data1.add(equip.get(i).getName());
                    equipList.add(equip.get(i));
                }
                //适配器
                ArrayAdapter<String> arr_adapter1 = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, adapter_data1);
                //设置样式
                arr_adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                map_sp_type.setAdapter(arr_adapter1);
                map_sp_type.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        if (map_sp_type.getSelectedItem().toString().trim().equals(equip.get(position).getName())) {
                            if (pointsList.size() > 0) {
                                Long mid = pointsList.get(pointsList.size() - 1).getId() + 1;
                                map_ed_name.setText(equip.get(position).getCode() + "-" + mid);
                            } else {
                                map_ed_name.setText(equip.get(position).getCode() + "-" + 1);
                            }
                        }
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {

                    }
                });
                break;
            default:
                final List<Equip> equip2 = getEquIp(2);
                map_sp_sort.setText("设备");
                List<String> adapter_data3 = new ArrayList<>();
                for (int i = 0, len = equip2.size(); i < len; i++) {
                    adapter_data3.add(equip2.get(i).getName());
                    equipList.add(equip2.get(i));
                }
                //适配器
                ArrayAdapter<String> arr_adapter3 = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, adapter_data3);
                //设置样式
                arr_adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                map_sp_type.setAdapter(arr_adapter3);
                map_sp_type.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        if (map_sp_type.getSelectedItem().toString().trim().equals(equip2.get(position).getName())) {
                            if (pointsList.size() > 0) {
                                Long mid = pointsList.get(pointsList.size() - 1).getId() + 1;
                                map_ed_name.setText(equip2.get(position).getCode() + "-" + mid);
                            } else {
                                map_ed_name.setText(equip2.get(position).getCode() + "-" + 1);
                            }
                        }
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {

                    }
                });
                break;
        }

        //点击完成时保存点的信息
        map_btn_add.setOnClickListener(v -> {
            map_tv_dixing_sort.setVisibility(View.GONE);
            map_ll_dixing_sort.setVisibility(View.GONE);
            //map_rl_add.setVisibility(View.GONE);
            if (!btn_model) {
                mBaiduMap.getUiSettings().setZoomGesturesEnabled(false);
            } else {
                mBaiduMap.getUiSettings().setZoomGesturesEnabled(true);
            }
            mBaiduMap.getUiSettings().setScrollGesturesEnabled(true);

            double lengths = 0;
            Points points = new Points();
            points.setId(null);
            UUID uuid = UUID.randomUUID();
            points.setUid(uuid + "");
            points.setItems_id(cid);
            points.setNote("备注信息：" + map_ed_note.getText().toString().trim());
            points.setLat(latLng.latitude + "");
            points.setLon(latLng.longitude + "");
            points.setBatch("0");
            for (int i = 0, len = equipList.size(); i < len; i++) {
                if (map_sp_type.getSelectedItem().toString().trim().equals(equipList.get(i).getName())) {
                    points.setEqu_id(equipList.get(i).getId());
                    points.setSblx(equipList.get(i).getName());
                    List<Points> pointsList1 = MyApplication.getInstances().getPointsDao().queryBuilder().build().list();
                    if (pointsList1.size() > 0) {
                        Long mid = pointsList1.get(pointsList1.size() - 1).getId() + 1;
                        points.setMark(equipList.get(i).getCode() + "-" + mid);
                    } else {
                        points.setMark(equipList.get(i).getCode() + "-" + 1);
                    }

                }
            }
            if (high != 0) {
                points.setHigh(high + "米");
            } else {
                points.setHigh("");
            }

            Line line = new Line();
            points.setName(name);
            points.setSbbh(map_sp_type.getSelectedItem().toString().trim());
            points.setOld(map_sp_state.getSelectedItem().toString().trim());


            points.setWhether("0");
            if (map_sp_equ.getSelectedItem() == null)
                points.setGlsb(glsb);
            else {
                points.setGlsb(map_sp_equ.getSelectedItem().toString().trim());
                final List<Points> pointsList12 = MyApplication.getInstances().getPointsDao().queryBuilder().where(PointsDao.Properties.Items_id.eq(cid), PointsDao.Properties.Whether.eq("0")).build().list();
                if (pointsList12.size() > 0) {
                    BigDecimal bg = new BigDecimal(Distance(Double.valueOf(latLng.latitude + ""), Double.valueOf(latLng.longitude + ""), Double.valueOf(pointsList12.get(pointsList12.size() - 1).getLat()), Double.valueOf(pointsList12.get(pointsList12.size() - 1).getLon()))).setScale(2, RoundingMode.UP);
                    lengths = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    List<Line> lineList = MyApplication.getInstances().getLineDao().queryBuilder().build().list();
                    line.setId(null);
                    line.setItem_id(cid);
                    line.setLatA(latLng.latitude + "");
                    line.setLonA(latLng.longitude + "");
                    line.setLatB(pointsList12.get(pointsList12.size() - 1).getLat());
                    line.setLonB(pointsList12.get(pointsList12.size() - 1).getLon());
                    line.setStart_id(points.getUid());
                    line.setEnd_id(uid);
                    line.setLength(lengths + "");
                    line.setBackNum("1");
                    if (pointsList12.get(pointsList12.size() - 1).getName().equals("杆塔") && points.getName().equals("杆塔")) {
                        //TODO 这里修改了                        line.setType("架空线路");
                        line.setType("");
                        line.setType_Id("11");
                        if (lineList.size() > 0) {
                            int mad = (int) (lineList.get(lineList.size() - 1).getId() + 1);
                            line.setName("架空线路-" + mad + "#");
                        } else {
                            line.setName("架空线路-" + 1 + "#");
                        }
                    } else {
                        line.setType("电缆");
                        line.setType_Id("12");
                        if (lineList.size() > 0) {
                            int mad = (int) (lineList.get(lineList.size() - 1).getId() + 1);
                            line.setName("电缆-" + mad + "#");
                        } else {
                            line.setName("电缆-" + 1 + "#");
                        }
                    }
                    line.setStatue("新建");
                    line.setNum("1");
                    //TODO 保存线
                    if (isOpenOrClose) {
                        MyApplication.getInstances().getLineDao().insert(line);
                        //TODO 这里是第一次关闭状态所以
                    } else {
                        setMapData();
                        isOpenOrClose = !isOpenOrClose;
                    }
                }
            }
            points.setDangju(lengths);
            MyApplication.getInstances().getPointsDao().insert(points);
            //添加marker
            addMap(latLng, points.getSblx(), points.getId(), points.getMark(), points.getOld());


            //添加marker时添加线
            initDatasPoints();
            List<Points> list;
            final List<Points> pointsList12 = MyApplication.getInstances().getPointsDao().queryBuilder().where(PointsDao.Properties.Items_id.eq(cid), PointsDao.Properties.Whether.eq("0"), PointsDao.Properties.Batch.eq("0")).build().list();
            Log.e("pointsList", pointsList12.toString());
            /*[Points{id=1, equ_id=1, high='1.1米', old='新建', lineType='null', items_id=1, note='备注信息：', mark='ZXG-1', sbbh='直线杆', sbzt='null', glsb='null', lat='39.08646762710225', lon='117.09919261745164', weizhi='null', dangju=0.0, name='杆塔', latA='null', latB='null', lonA='null', lonB='null', category='null', equ='null', whether='0', batch='0', sblx='直线杆', uid='6fbf99dd-e73b-469c-ac24-352be48f76ca'},
            Points{id=2, equ_id=1, high='1.1米', old='新建', lineType='null', items_id=1, note='备注信息：', mark='ZXG-2', sbbh='直线杆', sbzt='null', glsb='ZXG-1', lat='39.08610320177811', lon='117.09976908991655', weizhi='null', dangju=64.17, name='杆塔', latA='null', latB='null', lonA='null', lonB='null', category='null', equ='null', whether='0', batch='0', sblx='直线杆', uid='0267cbc2-e2da-4f2e-af47-dcf378baf44f'},
            Points{id=3, equ_id=1, high='1.1米', old='新建', lineType='null', items_id=1, note='备注信息：', mark='ZXG-3', sbbh='直线杆', sbzt='null', glsb='ZXG-2', lat='39.08569273425972', lon='117.0990925409082', weizhi='null', dangju=74.12, name='杆塔', latA='null', latB='null', lonA='null', lonB='null', category='null', equ='null', whether='0', batch='0', sblx='直线杆', uid='bbf6722d-2991-4567-aeca-eacbc28c0f68'}]

            [Points{id=1, equ_id=1, high='1.1米', old='新建', lineType='null', items_id=1, note='备注信息：', mark='ZXG-1', sbbh='直线杆', sbzt='null', glsb='null', lat='39.08646762710225', lon='117.09919261745164', weizhi='null', dangju=0.0, name='杆塔', latA='null', latB='null', lonA='null', lonB='null', category='null', equ='null', whether='0', batch='0', sblx='直线杆', uid='6fbf99dd-e73b-469c-ac24-352be48f76ca'},
            Points{id=2, equ_id=1, high='1.1米', old='新建', lineType='null', items_id=1, note='备注信息：', mark='ZXG-2', sbbh='直线杆', sbzt='null', glsb='ZXG-1', lat='39.08610320177811', lon='117.09976908991655', weizhi='null', dangju=64.17, name='杆塔', latA='null', latB='null', lonA='null', lonB='null', category='null', equ='null', whether='0', batch='0', sblx='直线杆', uid='0267cbc2-e2da-4f2e-af47-dcf378baf44f'},
            Points{id=3, equ_id=1, high='1.1米', old='新建', lineType='null', items_id=1, note='备注信息：', mark='ZXG-3', sbbh='直线杆', sbzt='null', glsb='ZXG-2', lat='39.08569273425972', lon='117.0990925409082', weizhi='null', dangju=74.12, name='杆塔', latA='null', latB='null', lonA='null', lonB='null', category='null', equ='null', whether='0', batch='0', sblx='直线杆', uid='bbf6722d-2991-4567-aeca-eacbc28c0f68'},
            Points{id=5, equ_id=1, high='1.1米', old='新建', lineType='null', items_id=1, note='备注信息：', mark='ZXG-5', sbbh='直线杆', sbzt='null', glsb='ZXG-3', lat='39.085848735588286', lon='117.09800257508161', weizhi='null', dangju=95.67, name='杆塔', latA='null', latB='null', lonA='null', lonB='null', category='null', equ='null', whether='0', batch='0', sblx='直线杆', uid='aea31c72-952c-4d18-a3cb-2044e2ba5f08'}]
*/
            List<LatLng> latLngList = new ArrayList<>();
            if (pointsList12.size() > 0)
                latLngList.add(new LatLng(Double.valueOf(pointsList12.get(pointsList12.size() - 1).getLat()), Double.valueOf(pointsList12.get(pointsList12.size() - 1).getLon())));
            if (pointsList12.size() > 1) {
                list = MyApplication.getInstances().getPointsDao().queryBuilder().where(PointsDao.Properties.Mark.eq(pointsList12.get(pointsList12.size() - 1).getGlsb())).build().list();
                if (list.size() > 0) {
                    latLngList.add(new LatLng(Double.valueOf(list.get(0).getLat()), Double.valueOf(list.get(0).getLon())));
                }
            }


            if (latLngList.size() > 1)
                //TODO 线 去添加线
                drawMyRoute(latLngList, pointsList12.get(pointsList12.size() - 2).getId(), pointsList12.get(pointsList12.size() - 1).getId(), lengths);
            jixukance = false;

            List<DefaultBean> defaultBeanList = getDefault(getId(points.getSblx()));
            if (defaultBeanList.size() > 0) {
                for (int i = 0; i < defaultBeanList.size(); i++) {
                    if (defaultBeanList.get(i).getType().equals("杆塔设备")) {
                        addGanta(defaultBeanList.get(i).getModelTypeName(), points.getId());
                    } else if (defaultBeanList.get(i).getType().equals("柱上设备")) {
                        addZhuShang(defaultBeanList.get(i).getModelTypeName(), points.getId());
                    }
                }

            }


            bottomSheetDialog.dismiss();
        });

        //点击取消时的操作
        Button cancel = bottomSheetDialog.findViewById(R.id.map_btn_cancel);
        assert cancel != null;
        cancel.setOnClickListener(v -> {
            bottomSheetDialog.dismiss();
            map_tv_dixing_sort.setVisibility(View.GONE);
            map_ll_dixing_sort.setVisibility(View.GONE);
            //map_rl_add.setVisibility(View.GONE);
            if (!btn_model) {
                mBaiduMap.getUiSettings().setZoomGesturesEnabled(false);
            } else {
                mBaiduMap.getUiSettings().setZoomGesturesEnabled(true);
            }
            mBaiduMap.getUiSettings().setScrollGesturesEnabled(true);
            mMapBtnTwo.setVisibility(View.VISIBLE);
            mMapBtnOne.setVisibility(View.VISIBLE);
            mMapBtnThree.setVisibility(View.VISIBLE);
            location.setVisibility(View.VISIBLE);
            jixukance = false;
        });
//给布局设置透明背景色
        //给布局设置透明背景色
        Objects.requireNonNull(bottomSheetDialog.getDelegate().findViewById(android.support.design.R.id.design_bottom_sheet));

        bottomSheetDialog.show();
        bottomSheetDialog.setOnDismissListener(dialogInterface -> {
            mBaiduMap.getUiSettings().setScrollGesturesEnabled(true);
            mBaiduMap.getUiSettings().setZoomGesturesEnabled(true);
        });
    }

    /**
     * 获取数据库中的信息
     *
     * @param id id
     * @return 集合
     */
    private List<DefaultBean> getDefault(int id) {
        List<DefaultBean> strings = null;
        try {
            strings = new ArrayList<>();
            SQLiteDatabase db = openDatabase(this);
            assert db != null;
            @SuppressLint("Recycle") Cursor cursor = db.rawQuery("select * from DefaultXH where equipTypeID=" + "'" + id + "'", null);//此处的db是表名，name是列名
            while (cursor.moveToNext()) {
                DefaultBean defaultBean = new DefaultBean();
                defaultBean.setUid(cursor.getString(0));
                defaultBean.setModelTypeId(cursor.getInt(1));
                defaultBean.setModelTypeName(cursor.getString(2));
                defaultBean.setEquidTypeId(cursor.getInt(7));
                defaultBean.setType(cursor.getString(8));
                defaultBean.setDefaultType(cursor.getString(9));
                defaultBean.setModleNum(cursor.getInt(10));
                strings.add(defaultBean);
            }
            cursor.close();
            db.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strings;
    }

    /**
     * 获取数据库中的ID
     *
     * @param str 根据表中名称进行判断
     * @return 返回对应ID
     */
    public int getId(String str) {
        int id = 0;
        SQLiteDatabase db = openDatabase(context);
        assert db != null;
        @SuppressLint("Recycle") Cursor cursor = db.rawQuery("select * from EquipType where name=" + "'" + str + "'", null);//此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            id = cursor.getInt(0);
        }
        cursor.close();
        db.close();
        return id;
    }

    /**
     * 添加柱上设备
     *
     * @param modelTypeName 设备名称
     * @param bid           设备ID
     */
    public void addZhuShang(String modelTypeName, Long bid) {
        Equipment equipment = new Equipment();
        equipment.setPoint_id(bid);
        equipment.setId(null);
        equipment.setQubie(2);
        equipment.setName(modelTypeName);
        equipment.setAmount(1);
        MyApplication.getInstances().getEquipmentDao().insert(equipment);
    }

    /**
     * 添加杆塔设备
     *
     * @param name 设备名称
     * @param cid  设备ID
     */
    public void addGanta(String name, Long cid) {
        Equipment equipment = new Equipment();
        equipment.setName(name);
        equipment.setPoint_id(cid);
        equipment.setId(null);
        equipment.setQubie(0);
        equipment.setAmount(1);
        MyApplication.getInstances().getEquipmentDao().insert(equipment);
    }

    /**
     * 添加图片
     *
     * @param x_zxg 图片资源ID
     */
    private void setImage(int x_zxg) {
        bitmap = BitmapFactory.decodeResource(getResources(), x_zxg);
    }

    /**
     * 添加覆盖物
     *
     * @param lspoint 经纬度信息
     * @param name    名称
     * @param mad     ID
     * @param mark    标题名称
     * @param old     利旧
     */
    private void addMap(final LatLng lspoint, final String name, final Long mad, final String mark, String old) {

        switch (old) {
            case "新建":
                switch (name) {
                    case "直线杆":
                        setImage(R.drawable.x_zxg);
                        break;
                    case "转角杆":
                        setImage(R.drawable.x_zjg);
                        break;
                    case "耐张杆":
                        setImage(R.drawable.x_nzg);
                        break;
                    case "终端杆":
                        setImage(R.drawable.x_zdg);
                        break;
                    case "柱上变压器":
                        setImage(R.drawable.x_zjz);
                        break;
                    case "配电室":
                        setImage(R.drawable.x_pds);
                        break;
                    case "环网箱":
                        setImage(R.drawable.x_hwx);
                        break;
                    case "开关站":
                        setImage(R.drawable.x_kgz);
                        break;
                    case "环网室":
                        setImage(R.drawable.x_hws);
                        break;
                    case "箱式变":
                        setImage(R.drawable.x_xsb);
                        break;
                    case "电缆分支箱":
                        setImage(R.drawable.x_dlf);
                        break;
                    case "变电站":
                        setImage(R.drawable.x_bdz);
                        break;
                    case "电缆井":
                        setImage(R.drawable.x_dlj);
                        break;
                    case "电缆拐点":
                        setImage(R.drawable.x_gd);
                        break;
                    case "通讯线":
                        setImage(R.drawable.x_dxd);
                        break;
                    case "高低压线":
                        setImage(R.drawable.x_dxd);
                        break;
                    case "道路":
                        setImage(R.drawable.x_dxd);
                        break;
                    case "河流":
                        setImage(R.drawable.x_dxd);
                        break;
                    case "建筑物":
                        setImage(R.drawable.x_dxd);
                        break;
                    default:
                        setImage(R.drawable.x_dxd);
                        break;
                }
                break;
            case "原有":
                switch (name) {
                    case "直线杆":
                        setImage(R.drawable.y_zxg);
                        break;
                    case "转角杆":
                        setImage(R.drawable.y_zjg);
                        break;
                    case "耐张杆":
                        setImage(R.drawable.y_nzg);
                        break;
                    case "终端杆":
                        setImage(R.drawable.y_zdg);
                        break;
                    case "柱上变压器":
                        setImage(R.drawable.y_zjz);
                        break;
                    case "配电室":
                        setImage(R.drawable.y_pds);
                        break;
                    case "环网箱":
                        setImage(R.drawable.y_hwx);
                        break;
                    case "开关站":
                        setImage(R.drawable.y_kgz);
                        break;
                    case "环网室":
                        setImage(R.drawable.y_hws);
                        break;
                    case "箱式变":
                        setImage(R.drawable.y_xsb);
                        break;
                    case "电缆分支箱":
                        setImage(R.drawable.y_dlf);
                        break;
                    case "变电站":
                        setImage(R.drawable.y_bdz);
                        break;
                    case "电缆井":
                        setImage(R.drawable.y_dlj);
                        break;
                    case "电缆拐点":
                        setImage(R.drawable.y_gd);
                        break;
                    case "通讯线":
                        setImage(R.drawable.y_dxd);
                        break;
                    case "高低压线":
                        setImage(R.drawable.y_dxd);
                        break;
                    case "道路":
                        setImage(R.drawable.y_dxd);
                        break;
                    case "河流":
                        setImage(R.drawable.y_dxd);
                        break;
                    case "建筑物":
                        setImage(R.drawable.y_dxd);
                        break;
                    default:
                        setImage(R.drawable.y_dxd);
                        break;
                }
                break;
            case "改造":
                switch (name) {
                    case "直线杆":
                        setImage(R.drawable.g_zxg);
                        break;
                    case "转角杆":
                        setImage(R.drawable.g_zjg);
                        break;
                    case "耐张杆":
                        setImage(R.drawable.g_nzg);
                        break;
                    case "终端杆":
                        setImage(R.drawable.g_zdg);
                        break;
                    case "柱上变压器":
                        setImage(R.drawable.g_zjz);
                        break;
                    case "配电室":
                        setImage(R.drawable.g_pds);
                        break;
                    case "环网箱":
                        setImage(R.drawable.g_hwx);
                        break;
                    case "开关站":
                        setImage(R.drawable.g_kgz);
                        break;
                    case "环网室":
                        setImage(R.drawable.g_hws);
                        break;
                    case "箱式变":
                        setImage(R.drawable.g_xsb);
                        break;
                    case "电缆分支箱":
                        setImage(R.drawable.g_dlf);
                        break;
                    case "变电站":
                        setImage(R.drawable.g_bdz);
                        break;
                    case "电缆井":
                        setImage(R.drawable.g_dlj);
                        break;
                    case "电缆拐点":
                        setImage(R.drawable.g_gd);
                        break;
                    case "通讯线":
                        setImage(R.drawable.g_dxd);
                        break;
                    case "高低压线":
                        setImage(R.drawable.g_dxd);
                        break;
                    case "道路":
                        setImage(R.drawable.g_dxd);
                        break;
                    case "河流":
                        setImage(R.drawable.g_dxd);
                        break;
                    case "建筑物":
                        setImage(R.drawable.g_dxd);
                        break;
                    default:
                        setImage(R.drawable.g_dxd);
                        break;
                }
                break;
            case "删除":
                switch (name) {
                    case "直线杆":
                        setImage(R.drawable.c_zxg);
                        break;
                    case "转角杆":
                        setImage(R.drawable.c_zjg);
                        break;
                    case "耐张杆":
                        setImage(R.drawable.c_nzg);
                        break;
                    case "终端杆":
                        setImage(R.drawable.c_zdg);
                        break;
                    case "柱上变压器":
                        setImage(R.drawable.c_zjz);
                        break;
                    case "配电室":
                        setImage(R.drawable.c_pds);
                        break;
                    case "环网箱":
                        setImage(R.drawable.c_hwx);
                        break;
                    case "开关站":
                        setImage(R.drawable.c_kgz);
                        break;
                    case "环网室":
                        setImage(R.drawable.c_hws);
                        break;
                    case "箱式变":
                        setImage(R.drawable.c_xsb);
                        break;
                    case "电缆分支箱":
                        setImage(R.drawable.c_dlf);
                        break;
                    case "变电站":
                        setImage(R.drawable.c_bdz);
                        break;
                    case "电缆井":
                        setImage(R.drawable.c_dlj);
                        break;
                    case "电缆拐点":
                        setImage(R.drawable.c_gd);
                        break;
                    case "通讯线":
                        setImage(R.drawable.c_dxd);
                        break;
                    case "高低压线":
                        setImage(R.drawable.c_dxd);
                        break;
                    case "道路":
                        setImage(R.drawable.c_dxd);
                        break;
                    case "河流":
                        setImage(R.drawable.c_dxd);
                        break;
                    case "建筑物":
                        setImage(R.drawable.c_dxd);
                        break;
                    default:
                        setImage(R.drawable.c_dxd);
                        break;
                }
                break;
        }

        map_marker.setText(mark);
        map_marker_image.setImageBitmap(bitmap);
        OverlayOptions option;
        BitmapDescriptor descriptor;
        if (btn_Name_isCheck) {
            descriptor = BitmapDescriptorFactory.fromView(view);
            option = new MarkerOptions()
                    .position(lspoint)
                    .animateType(MarkerOptions.MarkerAnimateType.none)
                    .title(mad + "")
                    .anchor(0.5f, 0.5f)//.anchor(0.5f, 1.0f)能显示出点。  .anchor(0.5f, 0.5f)覆盖住点
                    .icon(descriptor)
                    .draggable(false);//marker是否可拖拽
        } else {
            descriptor = BitmapDescriptorFactory.fromBitmap(bitmap);
            assert descriptor != null;
            option = new MarkerOptions()
                    .position(lspoint)
                    .animateType(MarkerOptions.MarkerAnimateType.none)
                    .title(mad + "")
                    .icon(descriptor)
                    .anchor(0.5f, 0.5f)
                    .draggable(false);//marker是否可拖拽
        }

        //添加marker
        mBaiduMap.addOverlay(option);

    }

    /**
     * 初始化地图
     */
    private void initMap() {

        WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        assert wm != null;
        wm.getDefaultDisplay().getMetrics(dm);

        densityDpi = dm.densityDpi;     // 屏幕密度dpi（120 / 160 / 240）

        //调用离线地图，否则第二次进入会加载不到
        MKOfflineMap mkOfflineMap = new MKOfflineMap();
        mkOfflineMap.init(this);
        setMapCustomFile();


        mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(mCurrentMode, true, null));
        /*MapStatus.Builder builder1 = new MapStatus.Builder();
        builder1.overlook(0);

        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder1.build()));*/

        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        // 定位初始化
        mLocClient = new LocationClient(this);     //声明LocationClient类
        mLocClient.registerLocationListener(myListener);    //注册监听函数
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Battery_Saving);//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        int span = 1000;
        option.setScanSpan(span);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps
        option.setLocationNotify(true);//可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤GPS仿真结果，默认需要
        option.setIsNeedAltitude(true);//设置海拔高度
        mLocClient.setLocOption(option);
        //开启定位
        mLocClient.start();

        pointsList = MyApplication.getInstances().getPointsDao().queryBuilder().where(PointsDao.Properties.Items_id.eq(cid)).build().list();
        if (pointsList.size() > 0) {
            for (int i = 0; i < pointsList.size(); i++) {
                latDoubleList.add(Double.parseDouble(pointsList.get(i).getLat()));
                lonDoubleList.add(Double.parseDouble(pointsList.get(i).getLon()));
            }
            LatLngBounds.Builder builder = new LatLngBounds.Builder();
            for (int x = 0; x < pointsList.size(); x++) {
                builder.include(new LatLng(Double.parseDouble(pointsList.get(x).getLat()), Double.parseDouble(pointsList.get(x).getLon())));
            }

            MapStatusUpdate u = MapStatusUpdateFactory.newLatLngBounds(builder.build());
            mBaiduMap.setMapStatus(u);
        }

        mBaiduMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {
            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus) {
                mapStatuss = mapStatus;
                lc = mapStatuss.target;
                setMapData();
            }

            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus, int i) {
                mapStatuss = mapStatus;
                lc = mapStatus.target;
            }

            @Override
            public void onMapStatusChange(MapStatus mapStatus) {
                mapStatuss = mapStatus;
                //移动地图时显示当前距离及连线
                lc = mapStatus.target;
                moveMap();
            }

            @Override
            public void onMapStatusChangeFinish(MapStatus mapStatus) {
                zoom = mapStatus.zoom;
                try {
                    //移动地图完成后的操作。
                    statusChangeFinish(mapStatus);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

    }

    //TODO 移动地图监听界面
    private void moveMap() {
        initDatasPoints();
        if (pointsListLine.size() > 0) {
            double pointLengths;
            List<LatLng> latLngList = new ArrayList<>();
            latLngList.add(mapStatuss.target);
            if (jixukance) {
                latLngList.add(new LatLng(Double.valueOf(jpoints.getLat()), Double.valueOf(jpoints.getLon())));
                pointLengths = new BigDecimal(Distance(Double.valueOf(jpoints.getLat()), Double.valueOf(jpoints.getLon()), mapStatuss.target.latitude, mapStatuss.target.longitude)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            } else {
                latLngList.add(new LatLng(Double.valueOf(pointsListLine.get(pointsListLine.size() - 1).getLat()), Double.valueOf(pointsListLine.get(pointsListLine.size() - 1).getLon())));
                pointLengths = new BigDecimal(Distance(Double.valueOf(pointsListLine.get(pointsListLine.size() - 1).getLat()), Double.valueOf(pointsListLine.get(pointsListLine.size() - 1).getLon()), mapStatuss.target.latitude, mapStatuss.target.longitude)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            }
            if (polyline != null)
                polyline.setPoints(latLngList);
            if (overlay != null) {
                overlay.setPosition(getLatLng(latLngList));
                overlay.setText(pointLengths + "米");
            }
        }
    }

    //TODO 设置当局和最后一个点虚线
    private void setMapData() {
        initLineData();
        if (polyline != null) {
            polyline.remove();
        }
        if (overlay != null) {
            overlay.remove();
        }
        if (pointsListLine.size() > 0) {
            double pointLengths;
            List<LatLng> latLngList = new ArrayList<>();
            if (jixukance) {
                latLngList.add(new LatLng(Double.valueOf(jpoints.getLat()), Double.valueOf(jpoints.getLon())));
                pointLengths = new BigDecimal(Distance(Double.valueOf(jpoints.getLat()), Double.valueOf(jpoints.getLon()), mapStatuss.target.latitude, mapStatuss.target.longitude)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            } else {
                latLngList.add(new LatLng(Double.valueOf(pointsListLine.get(pointsListLine.size() - 1).getLat()), Double.valueOf(pointsListLine.get(pointsListLine.size() - 1).getLon())));
                pointLengths = new BigDecimal(Distance(Double.valueOf(pointsListLine.get(pointsListLine.size() - 1).getLat()), Double.valueOf(pointsListLine.get(pointsListLine.size() - 1).getLon()), mapStatuss.target.latitude, mapStatuss.target.longitude)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            }
            //TODO 这里是最新点。
            latLngList.add(mapStatuss.target);
            //TODO 开关如果是关闭这里不进行绘制档距以及虚线。其他的不用管啦。
            if (isOpenOrClose) {
                drawMyRouteRealTime(latLngList);
                drawMyRouteRealName(getLatLng(latLngList), pointLengths);
            }
        }
    }

    private void initLineData() {
        pointsListLine = MyApplication.getInstances().getPointsDao().queryBuilder().where(PointsDao.Properties.Items_id.eq(cid), PointsDao.Properties.Whether.eq("0"), PointsDao.Properties.Batch.eq("0")).build().list();
    }

    /**
     * 设置离线地图config文件路径
     */
    private void setMapCustomFile() {
        String str = Environment.getExternalStorageState() + "/BaiduMapSDKNew/vmp/";
        File file = new File(str);
        if (!(file.exists())) {
            try {
                new File(str).createNewFile();
                InputStream input = openFileInput(str + ".cfg");
                FileOutputStream output = new FileOutputStream(str);
                byte[] buffer = new byte[8192];
                int i;
                while ((i = input.read(buffer)) > 0) {
                    output.write(buffer, 0, i);
                }
                output.close();
                input.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 拖动地图完成后进行的操作
     *
     * @param mapStatus MapStatus
     */
    private void statusChangeFinish(MapStatus mapStatus) {

        lc = mapStatus.target;
        latLngs.add(lc);
        //double保留几位小数
        DecimalFormat df = new DecimalFormat("0.00000");
        //如果当前位置和地图中心重合的话
        if (Double.parseDouble(df.format(mCurrentLat)) == Double.parseDouble(df.format(mapStatus.target.latitude)) && Double.parseDouble(df.format(mCurrentLon)) == Double.parseDouble(df.format(mapStatus.target.longitude))) {
            iv_center.setBackgroundResource(R.drawable.define_red);
        } else if (MARKER_DEFINE) {
            //如果处于移动坐标状态
            iv_center.setBackgroundResource(R.drawable.define_blue);
        } else {
            iv_center.setBackgroundResource(R.drawable.define_green);
        }

        initDatasPoints();
        if (pointsListLine.size() > 0) {
            double pointLengths;
            List<LatLng> latLngList = new ArrayList<>();
            latLngList.add(mapStatus.target);
            if (jixukance) {
                latLngList.add(new LatLng(Double.valueOf(jpoints.getLat()), Double.valueOf(jpoints.getLon())));
                pointLengths = new BigDecimal(Distance(Double.valueOf(jpoints.getLat()), Double.valueOf(jpoints.getLon()), mapStatus.target.latitude, mapStatus.target.longitude)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            } else {
                latLngList.add(new LatLng(Double.valueOf(pointsListLine.get(pointsListLine.size() - 1).getLat()), Double.valueOf(pointsListLine.get(pointsListLine.size() - 1).getLon())));
                pointLengths = new BigDecimal(Distance(Double.valueOf(pointsListLine.get(pointsListLine.size() - 1).getLat()), Double.valueOf(pointsListLine.get(pointsListLine.size() - 1).getLon()), mapStatus.target.latitude, mapStatus.target.longitude)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            }
            if (polyline != null)
                polyline.setPoints(latLngList);
            if (overlay != null) {
                overlay.setPosition(getLatLng(latLngList));
                overlay.setText(pointLengths + "米");
            }
        }

    }

    /**
     * 刷新数据
     */
    private void initDatasPoints() {
        pointsList = MyApplication.getInstances().getPointsDao().queryBuilder().where(PointsDao.Properties.Items_id.eq(cid)).build().list();
    }

    /**
     * 画实时连接显示距离的线
     *
     * @param latLngList 经纬度集合
     */
    @SuppressLint("SetTextI18n")
    private void drawMyRouteRealTime(List<LatLng> latLngList) {
        OverlayOptions ooPolyline = new PolylineOptions()
                .width(3)
                .color(Color.argb(160, 99, 189, 148))
                .dottedLine(true)
                .points(latLngList);
        polyline = (Polyline) mBaiduMap.addOverlay(ooPolyline);

    }

    /**
     * 画带有档距的线
     *
     * @param latLngList   经纬度信息
     * @param pointLengths 档距
     */
    @SuppressLint("SetTextI18n")
    private void drawMyRouteRealName(LatLng latLngList, double pointLengths) {

        OverlayOptions option;
        if (densityDpi > 320) {
            option = new TextOptions()
                    .position(latLngList)
                    .text(pointLengths + "米")
                    .zIndex(9)
                    .fontColor(Color.rgb(51, 51, 51))
                    .fontSize(35);
        } else {
            option = new TextOptions()
                    .position(latLngList)
                    .text(pointLengths + "米")
                    .zIndex(9)
                    .fontColor(Color.rgb(51, 51, 51))
                    .fontSize(24);
        }
        //添加marker
        overlay = (Text) mBaiduMap.addOverlay(option);
    }

    /**
     * 计算两点之间显示距离的经纬度
     *
     * @param latLngList 两点的经纬度集合
     * @return 两点中间点的经纬度信息
     */
    private LatLng getLatLng(List<LatLng> latLngList) {
        LatLng lng1 = new LatLng(latLngList.get(0).latitude, latLngList.get(0).longitude);
        LatLng lng2 = new LatLng(latLngList.get(1).latitude, latLngList.get(1).longitude);
        double aaa, bbb;
        if (lng1.longitude > lng2.longitude) {
            aaa = (lng1.longitude - lng2.longitude) / 2 + lng2.longitude;
        } else {
            aaa = (lng2.longitude - lng1.longitude) / 2 + lng1.longitude;
        }

        if (lng1.latitude > lng2.latitude) {
            bbb = (lng1.latitude - lng2.latitude) / 2 + lng2.latitude;
        } else {
            bbb = (lng2.latitude - lng1.latitude) / 2 + lng1.latitude;
        }
        return new LatLng(bbb, aaa);
    }

    /**
     * 移动到指定位置
     *
     * @param location 位置信息
     */
    private void navigateTo(BDLocation location) {
        if (isFirstLoc) {
            LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
            MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(ll);
            mBaiduMap.animateMapStatus(update);
            update = MapStatusUpdateFactory.zoomTo(18f);
            mBaiduMap.animateMapStatus(update);
            /*判断baiduMap是已经移动到指定位置*/
            if (mBaiduMap.getLocationData() != null)
                if (mBaiduMap.getLocationData().latitude == location.getLatitude()
                        && mBaiduMap.getLocationData().longitude == location.getLongitude()) {
                    isFirstLoc = false;
                }
        }
        MyLocationData.Builder locationBuilder =
                new MyLocationData.Builder();
        locationBuilder.latitude(location.getLatitude());
        locationBuilder.longitude(location.getLongitude());
        MyLocationData locationData = locationBuilder.build();
        mBaiduMap.setMyLocationData(locationData);
    }

    @Override
    public void onGetOfflineMapState(int i, int i1) {

    }


    @Override
    protected void onStop() {
        //取消注册传感器监听
        mSensorManager.unregisterListener(this);
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        // 退出时销毁定位
        mLocClient.stop();
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        mMapView.onDestroy();
        mMapView = null;
        latLngPolygon.clear();
        latLngs.clear();
        latLngPolygon = null;
        latLngs = null;
        if (bitmap != null && !bitmap.isRecycled()) {
            // 回收并且置为null
            bitmap.recycle();
        }
        super.onDestroy();
    }

    /**
     * 定位SDK监听函数
     */
    private class MyLocationListenner implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null || mMapView == null) {
                return;
            }
            mCurrentLat = location.getLatitude();
            mCurrentLon = location.getLongitude();
            mCurrentAccracy = location.getRadius();
            high = location.getAltitude();
            locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(mCurrentDirection).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);
            if (mCurrentLat != 4.9E-324 && mCurrentLon != 4.9E-324) {
                if (isFirstLoc) {
                    navigateTo(location);

                    LatLng ll = new LatLng(location.getLatitude(),
                            location.getLongitude());
                    MapStatus.Builder builder = new MapStatus.Builder();
                    builder.target(ll).zoom(19.0f);

                    mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));

                }
            }
        }
    }


}
